<script>
import { getWorkOrderListAPI, deleteOrderAPI, addOrderAPI, updateOrderAPI } from '@/apis/order'

export default {
  name: 'OrderList',
  data() {
    return {
      workOrderList: [],
      loading: false,
      dialogFormVisible: false,
      isEdit: false, // 标识是否为编辑模式
      form: {
        id: undefined,
        title: '',
        des: '',
        name: '',
        phone: '',
        address: '',
        payStatus: 0,
        status: 0,
        type: 0
      },
      // 添加查询表单数据
      queryForm: {
        id: '',
        title: '',
        name: ''
      },
      // 添加防抖定时器
      queryTimer: null,
      // 添加分页数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      rules: {
        title: [
          { required: true, message: '请输入工单标题', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchWorkOrderList()
  },
  methods: {
    async fetchWorkOrderList() {
      this.loading = true
      try {
        const res = await getWorkOrderListAPI()
        if (res.code === 0) {
          // 根据查询条件过滤数据
          let filteredData = res.data
          
          if (this.queryForm.id) {
            filteredData = filteredData.filter(item => 
              item.id && item.id.toString().includes(this.queryForm.id)
            )
          }
          
          if (this.queryForm.title) {
            filteredData = filteredData.filter(item => 
              item.title && item.title.includes(this.queryForm.title)
            )
          }
          
          if (this.queryForm.name) {
            filteredData = filteredData.filter(item => 
              item.name && item.name.includes(this.queryForm.name)
            )
          }
          
          // 按创建时间排序，最新的在前面
          filteredData.sort((a, b) => {
            const dateA = new Date(a.createTime || '')
            const dateB = new Date(b.createTime || '')
            return dateB - dateA
          })
          
          // 更新分页总数
          this.pagination.total = filteredData.length
          
          // 实现前端分页
          const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
          const end = start + this.pagination.pageSize
          const pagedData = filteredData.slice(start, end)
          
          this.workOrderList = pagedData.map(item => {
            return {
              id: item.id,
              title: item.title || '无标题',
              des: item.des || '无描述',
              name: item.name || '无联系人',
              phone: item.phone || '无联系电话',
              address: item.address || '无地址',
              payStatus: item.payStatus,
              status: item.status,
              pic: item.pic || '',
              productId: item.productId || '',
              dispatcherId: item.dispatcherId || '',
              employeeId: item.employeeId || '',
              type: item.type,
              createTime: item.createTime || new Date().toISOString(),
              updateTime: item.updateTime || new Date().toISOString()
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取工单列表失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取工单列表失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取工单列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    // 添加防抖查询功能
    debounceQuery() {
      // 清除之前的定时器
      if (this.queryTimer) {
        clearTimeout(this.queryTimer)
      }
      
      // 设置新的定时器
      this.queryTimer = setTimeout(() => {
        this.pagination.currentPage = 1
        this.fetchWorkOrderList()
      }, 300)
    },
    // 添加重置查询功能
    resetQuery() {
      this.queryForm = {
        id: '',
        title: '',
        name: ''
      }
      this.pagination.currentPage = 1
      this.fetchWorkOrderList()
    },
    // 处理分页大小变化
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize
      this.pagination.currentPage = 1
      this.fetchWorkOrderList()
    },
    // 处理当前页变化
    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage
      this.fetchWorkOrderList()
    },
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'warning'
        case 2:
          return 'success'
        case 3:
          return 'danger'
        case 4:
          return 'gray'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 1:
          return '处理中'
        case 2:
          return '已完成'
        case 3:
          return '已取消'
        case 4:
          return '已评价'
        default:
          return '待分配'
      }
    },
    getPayStatusType(payStatus) {
      switch (payStatus) {
        case 1:
          return 'success'
        default:
          return 'info'
      }
    },
    getPayStatusText(payStatus) {
      switch (payStatus) {
        case 1:
          return '已支付'
        default:
          return '未支付'
      }
    },
    getTypeText(type) {
      switch (type) {
        case 0:
          return '普通'
        case 1:
          return '紧急'
        default:
          return '未知类型'
      }
    },
    // 查看详情
    handleViewDetail(row) {
      this.$router.push({
        name: 'OrderDetail',
        query: {
          id: row.id
        }
      })
    },
    // 添加删除功能
    handleDelete(row) {
      this.$confirm(`确定要删除工单 "${row.title}" 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteOrderAPI(row.id)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 重新获取列表数据
            this.fetchWorkOrderList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg || '删除失败'
            })
          }
        } catch (error) {
          this.$message({
            type: 'error',
            message: '删除失败: ' + (error.msg || error.message || '未知错误')
          })
          console.error('删除失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加工单
    handleAdd() {
      this.$router.push({ name: 'OrderCreate' })
    },
    // 编辑工单
    handleEdit(row) {
      this.isEdit = true
      this.dialogFormVisible = true
      this.form = { ...row }
    },
    // 提交工单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let res
            if (this.isEdit) {
              // 编辑模式 - 更新工单
              res = await updateOrderAPI(this.form)
            } else {
              // 添加模式 - 添加工单
              res = await addOrderAPI(this.form)
            }
            
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: this.isEdit ? '更新工单成功!' : '添加工单成功!'
              })
              this.dialogFormVisible = false
              // 重新获取列表数据
              this.fetchWorkOrderList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg || (this.isEdit ? '更新工单失败' : '添加工单失败')
              })
            }
          } catch (error) {
            this.$message({
              type: 'error',
              message: (this.isEdit ? '更新工单失败: ' : '添加工单失败: ') + (error.msg || error.message || '未知错误')
            })
            console.error(this.isEdit ? '更新工单失败:' : '添加工单失败:', error)
          }
        } else {
          console.log('表单验证失败!')
          return false
        }
      })
    }
  }
}
</script>

<template>
  <div class="order-list">
    <h1 class="page-title">工单列表页面</h1>
    <div class="table-container">
      <!-- 查询表单 -->
      <el-card class="search-card">
        <el-form :model="queryForm" inline @submit.prevent="fetchWorkOrderList">
          <el-form-item label="工单ID">
            <el-input 
              v-model="queryForm.id" 
              placeholder="请输入工单ID" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="工单标题">
            <el-input 
              v-model="queryForm.title" 
              placeholder="请输入工单标题" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input 
              v-model="queryForm.name" 
              placeholder="请输入联系人" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 添加刷新和添加工单按钮 -->
      <div style="margin: 15px 0;">
        <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </el-button>
        <el-button type="primary" @click="handleAdd">添加工单</el-button>
      </div>
      
      <el-table :data="workOrderList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="工单ID" width="120" />
        <el-table-column prop="title" label="工单标题" width="180" />
        <el-table-column prop="name" label="联系人" width="100" />
        <el-table-column prop="status" label="工单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="工单类型" width="120">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加分页控件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px; text-align: center;">
      </el-pagination>
    </div>
    
    <!-- 添加工单对话框 -->
    <el-dialog :title="isEdit ? '编辑工单' : '添加工单'" v-model="dialogFormVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="工单描述" prop="des">
          <el-input v-model="form.des" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="form.payStatus" placeholder="请选择支付状态">
            <el-option label="未支付" :value="0"></el-option>
            <el-option label="已支付" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select v-model="form.status" placeholder="请选择工单状态">
            <el-option label="待分配" :value="0"></el-option>
            <el-option label="处理中" :value="1"></el-option>
            <el-option label="已完成" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单类型">
          <el-select v-model="form.type" placeholder="请选择工单类型">
            <el-option label="普通" :value="0"></el-option>
            <el-option label="紧急" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-list {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

.search-card {
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-card :deep(.el-card__body) {
  padding: 15px;
}

.dialog-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>